<template>

    <div class="register-div">
        <el-row type="flex" justify="center">
            <el-col :span="8">
                <el-card class="register-card" :body-style="{ padding: '0px' }">
                    <el-row class="logo-row" type="flex" justify="center">
                        <el-col :span="9">
                            <el-link :underline="false"><el-image :src="logoUrl"></el-image></el-link>
                        </el-col>
                    </el-row>
                    <el-form ref="form" :model="form" size="medium" :rules="rules" status-icon>
                        <el-row class="form-row" type="flex" justify="center">
                            <el-col :span="18">
                                <el-form-item label="用户名" prop="userName">
                                    <el-input v-model.trim="form.userName" placeholder="请输入用户名"></el-input>
                                </el-form-item>
                                <el-form-item label="密码" prop="password">
                                    <el-input type="password" v-model.trim="form.password" placeholder="请输入密码"></el-input>
                                </el-form-item>
                                <el-form-item label="确认密码" prop="checkPassword">
                                    <el-input type="password" v-model.trim="form.checkPassword" placeholder="请再次输入密码"></el-input>
                                </el-form-item>
                                <el-form-item label="真实姓名" prop="userRealName">
                                    <el-input class="realname" v-model.trim="form.userRealName" placeholder="请输入真实姓名"></el-input>
                                </el-form-item>
                                <el-form-item label="身份证号" prop="idCard">
                                    <el-input v-model.trim="form.idCard" placeholder="请输入身份证号"></el-input>
                                </el-form-item>
                                <el-form-item label="微信号" prop="wechatCode">
                                    <el-input v-model.trim="form.wechatCode" placeholder="请输入微信号"></el-input>
                                </el-form-item>
                                <el-form-item label="手机号" prop="phoneNum">
                                    <el-input v-model.number.trim="form.phoneNum" placeholder="请输入手机号"></el-input>
                                </el-form-item>
                                <el-form-item label="邮箱" prop="mailAddr">
                                    <el-input v-model.trim="form.mailAddr" placeholder="请输入邮箱"></el-input>
                                </el-form-item>
                                <el-form-item label="就读学校" prop="schoolName">
                                    <el-input v-model.trim="form.schoolName" placeholder="请输入就读学校"></el-input>
                                </el-form-item>
                                <el-form-item label="学号" prop="studentNum">
                                    <el-input  v-model.number.trim="form.studentNum" placeholder="请输入学号"></el-input>
                                </el-form-item>
                                <el-form-item>
                                    <el-button class="login-btn" @click="submit('form')" round size="small">注册</el-button>
                                    <el-button @click="resetForm('form')" round size="small">重置</el-button>
                                    <el-button class="back-btn" @click="back()" round size="small" icon="el-icon-back">返回</el-button>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </el-card>
            </el-col>
        </el-row>
    </div>
    
</template>

<script>
    export default {
        name: "Register",
        data(){
            var validateUsername = (rule, value, callback) => {
                axios.get('/validateUsernameAndPhoneNum', {
                    params: {
                        userName: value
                    }
                })
                    .then(response => {
                        if(response.data.success){
                            callback();
                        }else{
                            console.log(response);
                            callback(new Error(response.data.msg));
                        }
                    })
                    .catch(error => {
                        console.log(error);
                        callback(new Error());
                    })
                    .finally(() =>{
                    });
            };

            var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('密码不能为空'));
                } else {
                    if (this.form.checkPassword !== '') {
                        this.$refs.form.validateField('checkPassword');
                    }
                    callback();
                }
            };
            var validatePass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('确认密码不能为空'));
                } else if (value !== this.form.password) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
            var validateUserRealName = (rule, value, callback) => {
                if (value === '') {
                    callback();
                } else {
                    if (!/^.{2,40}$/.test(value)) {
                        callback(new Error('真实姓名长度应在4-40位之间'));
                    }else{
                        callback();
                    }
                }
            };

            var validateIdCard = (rule, value, callback) => {
                if (value === '') {
                    callback();
                } else {
                    if (!/^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(value)) {
                        callback(new Error('请输入正确的身份证'));
                    }else{
                        callback();
                    }
                }
            };

            var validatePhoneNum = (rule, value, callback) => {
                axios.get('/validateUsernameAndPhoneNum', {
                    params: {
                        phoneNum: value
                    }
                })
                    .then(response => {
                        if(response.data.success){
                            callback();
                        }else{
                            console.log(response);
                            callback(new Error("手机号已存在，请重新填写。"));
                        }
                    })
                    .catch(error => {
                        console.log(error);
                        callback(new Error());
                    })
                    .finally(() =>{
                    });
            };

            var validateMailAddr = (rule, value, callback) => {
                this.$axios.get('/validateUsernameAndPhoneNum', {
                    params: {
                        mailAddr: value
                    }
                })
                    .then(response => {
                        if(response.data.success){
                            callback();
                        }else{
                            console.log(response);
                            callback(new Error("邮箱已存在，请重新填写。"));
                        }
                    })
                    .catch(error => {
                        console.log(error);
                        callback(new Error());
                    })
                    .finally(() =>{
                    });
            };

            var validateSchoolName = (rule, value, callback) => {
                if (value === '') {
                    callback();
                } else {
                    if (!/^.{4,40}$/.test(value)) {
                        callback(new Error('学校名称长度应在4-40位之间'));
                    }else{
                        callback();
                    }
                }
            };

            var validateStudentNum = (rule, value, callback) => {
                if (value === '') {
                    callback();
                } else {
                    if (!/^[0-9]{4,40}$/.test(value)) {
                        callback(new Error('学号长度应位4-40位的数字'));
                    }else{
                        callback();
                    }
                }
            };

            return {
                logoUrl: require("../../assets/logo_64x64.png"),
                form: {
                    userName: "",
                    password: "",
                    checkPassword: "",
                    userRealName: "",
                    idCard: "",
                    wechatCode: "",
                    phoneNum: "",
                    mailAddr: "",
                    schoolName: "",
                    studentNum: ""
                },
                rules: {
                    userName: [
                        { required: true, message: '用户名不能为空', trigger: 'blur' },
                        { min: 2, max: 16, message: '用户名长度应在4-16位之间'},
                        { validator: validateUsername, trigger: 'blur' }
                    ],
                    password: [
                        { required: true, message: '密码不能为空', trigger: 'blur' },
                        { pattern: /^[a-zA-Z0-9]{6,18}$/, message: '密码应由6-18位字母和数字组成，不包含特殊字符。', trigger: ['blur', 'change'] },
                        { validator: validatePass, trigger: 'blur' }
                    ],
                    checkPassword: [
                        { required: true, message: '确认密码不能为空', trigger: 'blur' },
                        { validator: validatePass2, trigger: 'blur' }
                    ],
                    userRealName: [
                        { validator: validateUserRealName, trigger: ['blur', 'change'] }
                    ],
                    idCard: [
                        { validator: validateIdCard, trigger: ['blur', 'change'] }
                    ],
                    wechatCode: [
                        { required: true, message: '微信号不能为空', trigger: 'blur' },
                        { pattern: /^[a-zA-Z]([-_a-zA-Z0-9]{5,19})+$/, message: '请输入格式正确的微信号', trigger: ['blur', 'change'] }
                    ],
                    phoneNum: [
                        { required: true, message: '手机号不能为空', trigger: 'blur' },
                        { pattern: /^1[34578]\d{9}$/, message: '请输入正确的手机号', trigger: ['blur', 'change'] },
                        { validator: validatePhoneNum, trigger: 'blur' }
                    ],
                    mailAddr: [
                        { required: true, message: '邮箱不能为空', trigger: 'blur' },
                        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] },
                        { validator: validateMailAddr, trigger: 'blur' }
                    ],
                    schoolName: [
                        { validator: validateSchoolName, trigger: ['blur', 'change'] }
                    ],
                    studentNum: [
                        { validator: validateStudentNum, trigger: ['blur', 'change'] }
                    ]

                }
            }
        },
        methods: {
            submit(formName){
                this.$refs[formName].validate((valid) => {
                    var this01 = this;
                    delete this.form.checkPassword;
                    if (valid) {
                        axios.post(
                            '/register',
                            {
                                userInfo: this01.form,
                                normal: true
                            }
                        ).then(response =>{
                            if(response.data.success){
                                this.$router.push({name: "login"});
                            }else{
                                console.log("register error.");
                            }
                        }).catch(error => {

                        });
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },

            resetForm(formName) {
                this.$refs[formName].resetFields();
            },

            back(){
                this.$router.go(-1);
            }
        },
        components: {

        },
        beforeRouteEnter(to, from, next){
            //通过这种方式获取组件实例
            next(vm => {
                let isLogin = vm.$store.state.isLogin;
                if(isLogin){
                    vm.$message.error('您已登录，无需再次注册。');
                    next(from.path);
                }else{
                    next();
                }
            });
        }
    }
</script>

<style scoped>
    .el-row {
        height: auto;
    }

    .el-col {
        height: auto;
    }

    .register-div {
        background-color: #f0f0f0;
        height: 1280px;
    }

    .register-card {
        /*height: 1130px;*/
        margin-top: 100px;
    }

    .logo-row {
        margin-top: 30px;
    }

    .logo-row .el-link {
        left: 50%;
        transform: translateX(-50%);
    }

    .form-row {
        margin-top: 30px;
    }

    .form-row .el-button{
        color: #9e9e9e;
    }

    .login-btn{
        margin-left: 30%;
    }
</style>